package com.paradogs.framework.core.annoations.base;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Set;

/**
 * @author: yumi
 * @date: 2023/8/25  16:56
 * @Description: TODO
 */
@Slf4j
public abstract class BaseImportSelector extends BaseSelector implements ImportSelector {

    private AnnotationMetadata importingClassMetadata;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        super.beanFactory = beanFactory;
    }

    /**
     * 使用 @Import 引入时执行的逻辑
     * @param importingClassMetadata
     * @return
     */
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        this.importingClassMetadata = importingClassMetadata;
        return scanAndHandle();
    }

    /**
     * 设置扫描的路径
     * @return
     */
    public String[] getScanPackages() {
        try {
            // 获取被注解的类（启动类）的 Class，以及包路径
            String startupClassStr = importingClassMetadata.getClassName();
            Class<?> startupClass = Class.forName(startupClassStr);
            String startupPackage = startupClass.getPackage().getName();

            String[] result = new String[]{startupPackage};

            return result;

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理扫描到的 Bean
     * @param beanDefinition
     */
    public abstract void handle(BeanDefinition beanDefinition);
}
